package com.edee.bigday.order.web;

import com.edee.bigday.order.service.OrderService;
import com.edee.bigday.order.vo.OrderConfirmVo;
import com.edee.bigday.order.vo.OrderSubmitVo;
import com.edee.bigday.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    @Autowired
    OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model, HttpServletRequest request) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.comfirmOrder();
        model.addAttribute("orderConfirmData", confirmVo);
        //展示订确认信息：
        return "confirm";
    }

    /**
     * 下单功能
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes) {
        SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
        //创建订单、验令牌、验价、锁库存(在实现类com/edee/bigday/order/service/impl/OrderServiceImpl.java中完成)
        System.out.println("订单表单中的数据：" + vo);
        if (responseVo.getCode() == 0) {
            //下单成功，跳转到支付选择页：
            model.addAttribute("submitOrderResp",responseVo);
            return "pay";
        } else {
            //下单失败，重定向至订单确认页，重新确认订单信息:
            String msg = "下单失败：";
            switch (responseVo.getCode()){
                case 1: msg += "订单信息过期，请再次提交订单！";
                break;
                case 2: msg += "订单中的商品价格有变动，请确认后再次提交~";
                break;
                case 3: msg += "订单中的商品库存不足！请修改后再次提交吧~";
                break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.bigday.com/toTrade";
        }
    }
}
